package org.example.designmodel.future;

import org.example.utils.LogUtils;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class JavaFutureTest {

    private static final int TLEEP_CAP = 2000;

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        FutureTask<Boolean> hotWaterFuture = new FutureTask<>(new HotWater());
        FutureTask<Boolean> washCupFuture = new FutureTask<>(new WashCup());

        Thread hotWaterThread = new Thread(hotWaterFuture);
        Thread washCupThread = new Thread(washCupFuture);
        hotWaterThread.start();
        washCupThread.start();

        boolean hotWater = hotWaterFuture.get();
        boolean washCup = washCupFuture.get();

        drinkTea(hotWater, washCup);
    }

    public static void drinkTea(Boolean hotWater, Boolean washCup) {
        if (hotWater && washCup) {
            LogUtils.info("泡茶喝");
        } else if (hotWater) {
            LogUtils.info("水烧开了，没有茶壶");
        } else if (washCup) {
            LogUtils.info("茶壶洗干净了，但是烧水失败了");
        }
    }

    /**
     * 烧水线程
     */
    static class HotWater implements Callable<Boolean> {
        @Override
        public Boolean call() throws Exception {
            try {
                LogUtils.info("洗好水壶");
                LogUtils.info("灌上凉水");
                LogUtils.info("放在火上");
                Thread.sleep(TLEEP_CAP);
                LogUtils.info("水开了");
                return true;
            } catch (InterruptedException e) {
                LogUtils.info("烧水报错了");
                return false;
            }
        }
    }

    static class WashCup implements Callable<Boolean> {
        @Override
        public Boolean call() throws Exception {
            try {
                LogUtils.info("洗茶壶");
                LogUtils.info("洗茶杯");
                LogUtils.info("拿茶叶");
                Thread.sleep(TLEEP_CAP);
                LogUtils.info("洗完了");
                return true;
            } catch (InterruptedException e) {
                LogUtils.info("洗茶壶失败了");
                return false;
            }
        }
    }
}
